<template>
  <div class="message-send">
    <el-card class="send-card">
      <template #header>
        <div class="card-header">
          <span>发送消息</span>
          <el-button type="primary" @click="handleSend" :loading="sending">发送</el-button>
        </div>
      </template>

      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <!-- 消息类型 -->
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择消息类型" @change="handleTypeChange">
            <el-option
              v-for="item in messageTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- 消息模板 -->
        <el-form-item label="消息模板" prop="templateId">
          <el-select
            v-model="formData.templateId"
            placeholder="请选择消息模板"
            filterable
            @change="handleTemplateChange"
          >
            <el-option
              v-for="item in templateList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-button type="primary" link @click="openTemplateDialog">管理模板</el-button>
        </el-form-item>

        <!-- 消息标题 -->
        <el-form-item label="消息标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入消息标题" />
        </el-form-item>

        <!-- 消息内容 -->
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="6"
            placeholder="请输入消息内容"
          />
          <div class="content-tips">
            <p>支持变量替换，可用变量：</p>
            <el-tag
              v-for="(item, index) in templateVariables"
              :key="index"
              class="variable-tag"
              @click="insertVariable(item)"
            >
              {{ item }}
            </el-tag>
          </div>
        </el-form-item>

        <!-- 发送方式 -->
        <el-form-item label="发送方式" prop="methods">
          <el-checkbox-group v-model="formData.methods">
            <el-checkbox
              v-for="item in messageMethods"
              :key="item.value"
              :label="item.value"
            >
              {{ item.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <!-- 接收者 -->
        <el-form-item label="接收者" prop="receivers">
          <el-select
            v-model="formData.receivers"
            multiple
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userSearchLoading"
            placeholder="请选择接收者"
          >
            <el-option
              v-for="item in userOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span>{{ item.name }}</span>
              <span class="user-info">{{ item.department }} - {{ item.position }}</span>
            </el-option>
          </el-select>
          <div class="receiver-actions">
            <el-button type="primary" link @click="openReceiverDialog">选择部门</el-button>
            <el-button type="primary" link @click="openRoleDialog">选择角色</el-button>
          </div>
        </el-form-item>

        <!-- 发送时间 -->
        <el-form-item label="发送时间">
          <el-radio-group v-model="formData.sendType">
            <el-radio label="now">立即发送</el-radio>
            <el-radio label="schedule">定时发送</el-radio>
          </el-radio-group>
          <el-date-picker
            v-if="formData.sendType === 'schedule'"
            v-model="formData.scheduleTime"
            type="datetime"
            placeholder="请选择发送时间"
            :disabled-date="disabledDate"
            :disabled-time="disabledTime"
          />
        </el-form-item>

        <!-- 高级选项 -->
        <el-form-item label="高级选项">
          <el-collapse>
            <el-collapse-item title="高级设置" name="1">
              <el-form-item label="优先级">
                <el-radio-group v-model="formData.priority">
                  <el-radio label="high">高</el-radio>
                  <el-radio label="normal">中</el-radio>
                  <el-radio label="low">低</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否需要回执">
                <el-switch v-model="formData.needReceipt" />
              </el-form-item>
              <el-form-item label="过期时间">
                <el-date-picker
                  v-model="formData.expireTime"
                  type="datetime"
                  placeholder="请选择过期时间"
                  :disabled-date="disabledDate"
                />
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 模板管理对话框 -->
    <el-dialog v-model="templateDialogVisible" title="消息模板管理" width="800px">
      <template-management @select="handleTemplateSelect" />
    </el-dialog>

    <!-- 部门选择对话框 -->
    <el-dialog v-model="departmentDialogVisible" title="选择部门" width="600px">
      <el-tree
        ref="departmentTree"
        :data="departmentList"
        :props="{ label: 'name', children: 'children' }"
        show-checkbox
        node-key="id"
        @check="handleDepartmentCheck"
      />
      <template #footer>
        <el-button @click="departmentDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDepartmentSelect">确定</el-button>
      </template>
    </el-dialog>

    <!-- 角色选择对话框 -->
    <el-dialog v-model="roleDialogVisible" title="选择角色" width="600px">
      <el-table
        :data="roleList"
        border
        @selection-change="handleRoleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="description" label="描述" />
      </el-table>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRoleSelect">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  sendMessage,
  getMessageTypes,
  getMessageMethods,
  getMessageTemplateList,
  searchUsers
} from '@/api/message'
import TemplateManagement from '../template/index.vue'

const router = useRouter()
const formRef = ref(null)
const sending = ref(false)
const userSearchLoading = ref(false)
const userOptions = ref([])
const templateList = ref([])
const departmentList = ref([])
const roleList = ref([])
const selectedRoles = ref([])

// 对话框显示状态
const templateDialogVisible = ref(false)
const departmentDialogVisible = ref(false)
const roleDialogVisible = ref(false)

// 消息类型和发送方式
const messageTypes = ref([])
const messageMethods = ref([])

// 模板变量
const templateVariables = [
  '${userName}',
  '${department}',
  '${position}',
  '${company}',
  '${date}',
  '${time}'
]

// 表单数据
const formData = reactive({
  type: '',
  templateId: '',
  title: '',
  content: '',
  methods: [],
  receivers: [],
  sendType: 'now',
  scheduleTime: null,
  priority: 'normal',
  needReceipt: false,
  expireTime: null
})

// 表单验证规则
const rules = {
  type: [{ required: true, message: '请选择消息类型', trigger: 'change' }],
  title: [{ required: true, message: '请输入消息标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入消息内容', trigger: 'blur' }],
  methods: [{ required: true, message: '请选择发送方式', trigger: 'change' }],
  receivers: [{ required: true, message: '请选择接收者', trigger: 'change' }]
}

// 初始化数据
onMounted(async () => {
  await Promise.all([
    fetchMessageTypes(),
    fetchMessageMethods(),
    fetchTemplateList()
  ])
})

// 获取消息类型
const fetchMessageTypes = async () => {
  try {
    const res = await getMessageTypes()
    messageTypes.value = res.data
  } catch (error) {
    console.error('获取消息类型失败:', error)
  }
}

// 获取发送方式
const fetchMessageMethods = async () => {
  try {
    const res = await getMessageMethods()
    messageMethods.value = res.data
  } catch (error) {
    console.error('获取发送方式失败:', error)
  }
}

// 获取模板列表
const fetchTemplateList = async () => {
  try {
    const res = await getMessageTemplateList()
    templateList.value = res.data
  } catch (error) {
    console.error('获取模板列表失败:', error)
  }
}

// 搜索用户
const searchUsers = async (query) => {
  if (query) {
    userSearchLoading.value = true
    try {
      const res = await searchUsers({ keyword: query })
      userOptions.value = res.data
    } catch (error) {
      console.error('搜索用户失败:', error)
    } finally {
      userSearchLoading.value = false
    }
  }
}

// 处理消息类型变更
const handleTypeChange = (value) => {
  // 根据消息类型筛选模板
  fetchTemplateList({ type: value })
}

// 处理模板变更
const handleTemplateChange = (templateId) => {
  const template = templateList.value.find(t => t.id === templateId)
  if (template) {
    formData.title = template.title
    formData.content = template.content
  }
}

// 插入变量
const insertVariable = (variable) => {
  const textarea = document.querySelector('textarea')
  const start = textarea.selectionStart
  const end = textarea.selectionEnd
  formData.content = formData.content.substring(0, start) + variable + formData.content.substring(end)
}

// 打开模板管理对话框
const openTemplateDialog = () => {
  templateDialogVisible.value = true
}

// 选择模板
const handleTemplateSelect = (template) => {
  formData.templateId = template.id
  handleTemplateChange(template.id)
  templateDialogVisible.value = false
}

// 打开部门选择对话框
const openReceiverDialog = () => {
  departmentDialogVisible.value = true
}

// 处理部门选择
const handleDepartmentCheck = (data, checked) => {
  // 处理部门选择逻辑
}

// 确认部门选择
const confirmDepartmentSelect = () => {
  const checkedNodes = departmentTree.value.getCheckedNodes()
  // 处理选中的部门
  departmentDialogVisible.value = false
}

// 打开角色选择对话框
const openRoleDialog = () => {
  roleDialogVisible.value = true
}

// 处理角色选择
const handleRoleSelectionChange = (selection) => {
  selectedRoles.value = selection
}

// 确认角色选择
const confirmRoleSelect = () => {
  // 处理选中的角色
  roleDialogVisible.value = false
}

// 日期禁用
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7
}

const disabledTime = (date) => {
  if (date && date.getTime() < Date.now()) {
    return {
      hours: () => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
      minutes: () => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
      seconds: () => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59]
    }
  }
  return {}
}

// 发送消息
const handleSend = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    sending.value = true
    const data = {
      ...formData,
      scheduleTime: formData.sendType === 'schedule' ? formData.scheduleTime : null
    }
    
    await sendMessage(data)
    ElMessage.success('发送成功')
    router.push('/message/center')
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error(error.message || '发送失败')
  } finally {
    sending.value = false
  }
}
</script>

<style lang="scss" scoped>
.message-send {
  padding: 20px;

  .send-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .content-tips {
      margin-top: 8px;
      color: #909399;
      font-size: 12px;

      .variable-tag {
        margin: 4px;
        cursor: pointer;
      }
    }

    .receiver-actions {
      margin-top: 8px;
    }

    .user-info {
      color: #909399;
      font-size: 12px;
      margin-left: 8px;
    }
  }
}
</style> 